import { ref } from 'vue'

const createPage = () => {
  return {
    pageSize: 20,
    pageNum: 0,
    total: 0
  }
}

function usePage(queryServe: (params: any) => Promise<any>) {
  const page = ref(createPage())
  const list = ref([])
  const loading = ref(false)
  const finished = ref(false)

  const refreshing = ref(true)

  const error = ref(false)

  const reset = () => {
    page.value = createPage()
    list.value = []
    loading.value = false
    finished.value = false
  }

  const refresh = (params: any) => {
    query(params, true)
  }

  const query = (params: any, refresh?: boolean) => {
    console.log('query', params, refresh, page.value)
    if (refresh) {
      error.value = false
      page.value = createPage()
    } else {
      loading.value = true
    }
    if (error.value) return Promise.resolve()
    return new Promise<void>(resolve => {
      queryServe({
        pageSize: page.value.pageSize,
        pageNum: page.value.pageNum + 1,
        ...params
      })
        .then(resp => {
          if (resp.code == 0) {
            const { data } = resp
            const { records, current, pages, total } = data
            page.value.total = total
            if (+current >= +pages) {
              finished.value = true
            }
            if (refresh) {
              list.value = records
            } else {
              list.value = list.value.concat(records)
            }
            page.value.pageNum++
          } else {
            error.value = true
          }
        })
        .catch(() => {
          error.value = true
        })
        .finally(() => {
          loading.value = false
          refreshing.value = false
          resolve()
        })
    })
  }

  return {
    page,
    list,
    loading,
    finished,
    reset,
    query,
    refresh,
    refreshing
  }
}

export default usePage
